﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace OrderManagementSystem
{
    public class OrderDetails
    {
        public string GoodsName { get; set; }
        public decimal UnitPrice { get; set; }
        public int Quantity { get; set; }

        public override bool Equals(object obj)
        {
            return obj is OrderDetails details &&
                   GoodsName == details.GoodsName &&
                   UnitPrice == details.UnitPrice &&
                   Quantity == details.Quantity;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(GoodsName, UnitPrice, Quantity);
        }

        public override string ToString()
        {
            return $"{GoodsName} (单价：{UnitPrice:C}，数量：{Quantity})";
        }
    }

    public class Order
    {
        public string OrderId { get; set; }
        public string Customer { get; set; }
        public List<OrderDetails> Details { get; } = new List<OrderDetails>();

        public decimal TotalAmount => Details.Sum(d => d.UnitPrice * d.Quantity);

        public override bool Equals(object obj)
        {
            return obj is Order order &&
                   OrderId == order.OrderId;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(OrderId);
        }

        public override string ToString()
        {
            return $"订单号：{OrderId}\n客户：{Customer}\n总金额：{TotalAmount:C}\n明细：\n{string.Join("\n", Details)}";
        }

    }

    public class OrderService
    {
        private List<Order> orders = new List<Order>();

        public void AddOrder(Order order)
        {
            if (orders.Contains(order))
                throw new InvalidOperationException("订单已存在");
            orders.Add(order);
        }

        public void RemoveOrder(string orderId)
        {
            var order = orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
                throw new KeyNotFoundException("找不到要删除的订单");
            orders.Remove(order);
        }

        public void UpdateOrder(Order newOrder)
        {
            var index = orders.FindIndex(o => o.OrderId == newOrder.OrderId);
            if (index == -1)
                throw new KeyNotFoundException("找不到要修改的订单");
            orders[index] = newOrder;
        }

        // 使用LINQ实现查询
        public IEnumerable<Order> QueryOrders(
            Func<Order, bool> predicate = null,
            Comparison<Order> sortComparison = null)
        {
            var query = orders.AsEnumerable();

            if (predicate != null)
                query = query.Where(predicate);

            return sortComparison != null
                ? query.OrderBy(o => o, new ComparisonComparer<Order>(sortComparison))
                : query.OrderBy(o => o.TotalAmount);
        }

        // 排序方法
        public void SortOrders(Comparison<Order> comparison = null)
        {
            if (comparison == null)
                orders.Sort((a, b) => a.OrderId.CompareTo(b.OrderId));
            else
                orders.Sort(comparison);
        }

        // 自定义比较器
        private class ComparisonComparer<T> : IComparer<T>
        {
            private readonly Comparison<T> comparison;
            public ComparisonComparer(Comparison<T> comparison) => this.comparison = comparison;
            public int Compare(T x, T y) => comparison(x, y);
        }
    }

    class Program
    {
        static OrderService service = new OrderService();

        static void Main()
        {
            while (true)
            {
                Console.WriteLine("\n1. 添加订单\n2. 删除订单\n3. 修改订单\n4. 查询订单\n5. 退出");
                Console.Write("请选择操作：");
                switch (Console.ReadLine())
                {
                    case "1": AddOrder(); break;
                    case "2": RemoveOrder(); break;
                    case "3": UpdateOrder(); break;
                    case "4": QueryOrders(); break;
                    case "5": return;
                }
            }
        }

        static void AddOrder()
        {
            try
            {
                var order = new Order();
                Console.Write("输入订单号：");
                order.OrderId = Console.ReadLine();
                Console.Write("输入客户名：");
                order.Customer = Console.ReadLine();

                while (true)
                {
                    var detail = new OrderDetails();
                    Console.Write("输入商品名（回车结束）：");
                    var name = Console.ReadLine();
                    if (string.IsNullOrEmpty(name)) break;

                    detail.GoodsName = name;
                    Console.Write("输入单价：");
                    detail.UnitPrice = decimal.Parse(Console.ReadLine());
                    Console.Write("输入数量：");
                    detail.Quantity = int.Parse(Console.ReadLine());

                    if (order.Details.Contains(detail))
                        Console.WriteLine("该商品明细已存在！");
                    else
                        order.Details.Add(detail);
                }

                service.AddOrder(order);
                Console.WriteLine("订单添加成功！");
            }
            catch (Exception e) { ShowError(e); }
        }

        static void RemoveOrder()
        {
            try
            {
                Console.Write("输入要删除的订单号：");
                service.RemoveOrder(Console.ReadLine());
                Console.WriteLine("订单删除成功！");
            }
            catch (Exception e) { ShowError(e); }
        }

        static void QueryOrders()
        {
            Console.Write("查询条件（1.订单号 2.商品 3.客户 4.金额范围）：");
            var condition = Console.ReadLine();
            IEnumerable<Order> result = null;

            switch (condition)
            {
                case "1":
                    Console.Write("输入订单号：");
                    result = service.QueryOrders(o => o.OrderId == Console.ReadLine());
                    break;
                case "2":
                    Console.Write("输入商品名：");
                    result = service.QueryOrders(o => o.Details.Any(d => d.GoodsName == Console.ReadLine()));
                    break;
                case "3":
                    Console.Write("输入客户名：");
                    result = service.QueryOrders(o => o.Customer == Console.ReadLine());
                    break;
                case "4":
                    Console.Write("输入最小金额：");
                    var min = decimal.Parse(Console.ReadLine());
                    Console.Write("输入最大金额：");
                    result = service.QueryOrders(o => o.TotalAmount >= min && o.TotalAmount <= decimal.Parse(Console.ReadLine()));
                    break;
            }

            if (result?.Any() == true)
                foreach (var order in result)
                    Console.WriteLine($"\n{order}");
            else
                Console.WriteLine("没有找到符合条件的订单");
        }

        static void UpdateOrder()
        {
            try
            {
                Console.Write("输入要修改的订单号：");
                var oldOrder = service.QueryOrders(o => o.OrderId == Console.ReadLine()).FirstOrDefault();
                if (oldOrder == null) throw new KeyNotFoundException("订单不存在");

                var newOrder = new Order { OrderId = oldOrder.OrderId };
                Console.Write($"新客户名（原：{oldOrder.Customer}）：");
                newOrder.Customer = Console.ReadLine();

                // 复制原有明细
                foreach (var detail in oldOrder.Details)
                    newOrder.Details.Add(detail);

                service.UpdateOrder(newOrder);
                Console.WriteLine("订单修改成功！");
            }
            catch (Exception e) { ShowError(e); }
        }

        static void ShowError(Exception e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"操作失败：{e.Message}");
            Console.ResetColor();
        }
    }
}

